﻿// Copyright (c) Vitaly Kamiansky. All rights reserved. 
// See License.txt in the project root.

using System;
using System.ComponentModel;

namespace Property.Workers
{
    public class RetryFunctionWorkerDecorator<T> : FunctionWorkerDecorator<T>
    {
        protected RetryFunctionWorkerDecorator(IFunctionWorkerPrototype<T> compositionBasePrototype, Func<T> getValue, int retryCount)
            : base(compositionBasePrototype, getValue)
        {
            if (retryCount < 1) throw new ArgumentOutOfRangeException("retryCount");

            _RetryCount = retryCount;
        }

        //=//

        private readonly int _RetryCount;
        private int TriesState;

        protected override void Completed(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error == null || ++TriesState >= _RetryCount)
                OnRunWorkerCompleted(e);
            else
                _CompositionBase.RunWorkerAsync();
        }

        public override void RunWorkerAsync()
        {
            TriesState = 0;
            _CompositionBase.RunWorkerAsync();
        }
    }
}
